using System;
using System.IO;
using UnityEngine;
using LS.Digitize;

namespace LS.Digitize
{
    public sealed class Vector2IntSerializer: CompoundSerializer<Vector2Int>
    {
        public Vector2IntSerializer() : base(typeof(Vector2Int),typeof(int))
        {
            
        }
        
        public override void WriteData(IWriter writer, Vector2Int obj)
        {
            ISerializer subSerializer = SubSerializer;
            using (writer.WriteObjectScope())
            {
                if (subSerializer is PrimitiveSerializer<int> ps)
                {
                    using (writer.WritePropertyScope("x"))
                        ps.WriteData(writer, obj.x);
                    
                    using (writer.WritePropertyScope("y"))
                        ps.WriteData(writer, obj.y);
                }
                else
                {
                    using (writer.WritePropertyScope("x"))
                        subSerializer.Write(writer, obj.x);
                    
                    using (writer.WritePropertyScope("y"))
                        subSerializer.Write(writer, obj.y);
                }
            }
        }

        public override Vector2Int ReadData(IReader reader)
        {
            ISerializer subSerializer = SubSerializer;
            Vector2Int target = default;
            using (var objScope = reader.ReadObjectScope())
            {
                string propertyName = null;
                if (subSerializer is PrimitiveSerializer<int> ps)
                {
                    propertyName = reader.ReadPropertyName();
                    int x = ps.ReadData(reader);
                    propertyName = reader.ReadPropertyName();
                    int y = ps.ReadData(reader);
                    target = new Vector2Int(x, y);
                }
                else
                {
                    propertyName = reader.ReadPropertyName();
                    int x = (int)subSerializer.Read(reader);
                    propertyName = reader.ReadPropertyName();
                    int y = (int)subSerializer.Read(reader);
                    target = new Vector2Int(x, y);
                }
            }

            return target;
        }
        
        public override void ReadInto(IReader reader, ref Vector2Int obj)
        {
            obj = ReadData(reader);
        }
    }
}